from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, HttpUrl

from app.services.locator_service import LocatorService


class LocateRequest(BaseModel):
    url: HttpUrl
    xpath: str
    css: str | None = None


class CandidateResponse(BaseModel):
    xpath: str
    css: str | None
    strategy: str
    matches: int
    verification_status: str


class LocateResponse(BaseModel):
    original_node_html: str
    original_node_attributes: dict[str, str]
    candidates: list[CandidateResponse]


router = APIRouter(prefix="/locate", tags=["locate"])
service = LocatorService()


@router.post("/analyze", response_model=LocateResponse)
async def analyze_locate(request: LocateRequest) -> LocateResponse:
    try:
        return await service.process_request(request)
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error))
    except Exception as error:
        raise HTTPException(status_code=500, detail="Internal server error") from error
